package tw.com.book.componet;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import tw.com.book.domain.V001Type;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class CursorUtils {
	private static final String TAG = CursorUtils.class.getCanonicalName();

	public static <T> List<T> toConvertz(Cursor cursr, Class<T> pClass,
			Context ct) throws IssueBussinessException {

		final List<T> reValues = new ArrayList<T>();
		if (cursr.getCount() == 0) {
			return reValues;
		}

		try {
			cursr.moveToFirst();
			final TableContent table = VoUtils.getApp(pClass, ct);
			for (int i = 0; i < cursr.getCount(); i++) {
				T obj = pClass.newInstance();
				for (PairValue p : table.getPairs()) {
					final int index = cursr
							.getColumnIndex(p.getFileTableName());
					String str = cursr.getString(index);

					setBeanValue(obj, p.getFielName(), str);

				}
				reValues.add(obj);
				cursr.moveToNext();

			}
			return reValues;
		} catch (Exception e) {
			Log.v(TAG, e.getMessage());
			throw new IssueBussinessException(Msg.W001);
		}

	}

	private static void setBeanValue(Object obj, String name, Object value) {

		try {
			final Field f = obj.getClass().getDeclaredField(name);
			f.setAccessible(true);
			f.set(obj, value);
			f.setAccessible(false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
